package com.zrf.excelExport.controller;

import com.zrf.excelExport.service.ExportService;
import com.zrf.excelExport.vo.FileInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据导出controller
 * @author zrf
 *         Created by zrf on 2017/1/1.
 */
@Controller
public class ExportController {
    /**
     * excel日期导出格式
     */
    private DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmm");
    /**
     * 导出service
     */
    @Resource
    private ExportService exportService;
    /**
     * 自定义sql文件路径
     */
    @Value("${sqlFilePath}")
    private String sqlFilePath;

    /**
     * 首页
     * @param model model
     * @param path sql目录
     * @return index
     */
    @RequestMapping("/")
    public String index(ModelMap model, String path){
        if(path == null){
            path = "";
        }
        File file = new File(sqlFilePath + "/" + path);
        if(file.isDirectory()){
            File[] listFiles = file.listFiles();

            List<FileInfo> fileInfoList = new ArrayList<>();
            for (File item : listFiles) {
                String name = item.getName();
                if(!name.endsWith("xlsx")) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setFileName(name);
                    fileInfo.setDir(item.isDirectory());
                    fileInfoList.add(fileInfo);
                }
            }
            model.addAttribute("fileInfoList", fileInfoList);
        }

        return "sqlFileList";
    }

    /**
     * 根据文件内容中的sql，将文件中的sql查询结果导出
     * @param sqlFileName sql 文件名称
     * @param response response
     * @throws IOException stream flush close exception
     */
    @RequestMapping("/excel/export")
    public void export(String sqlFileName, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        String excelName = FilenameUtils.getBaseName(sqlFileName) + "_" + dateFormat.format(new Date()) + ".xlsx";
        response.setHeader("content-disposition", "attachment;filename=" +
                URLEncoder.encode(excelName, "UTF-8"));
        exportService.exportExcel(sqlFilePath, sqlFileName, outputStream);



        outputStream.flush();
        outputStream.close();
    }
}
